package com.edu.lwh.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.edu.lwh.pojo.Account;
import com.edu.lwh.pojo.ThreadLocalUtil;
import com.edu.lwh.pojo.User;
import com.edu.lwh.service.AccountService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 会哥
 * @since 2024-09-15
 */
@RestController
@RequestMapping("/account")
@Transactional
public class AccountController {

    @Resource
    private AccountService accountService;
    User user = ThreadLocalUtil.get();

    /**
     * 存钱
     * @param money
     */
    @PostMapping("save")
    public void SaveAccount(@RequestParam("money") Integer money){

        LambdaQueryWrapper<Account> wrapper = Wrappers.<Account>lambdaQuery()
                .eq(Account::getUid, user.getUid());
        Account one = this.accountService.getOne(wrapper);
        if(ObjectUtils.isEmpty(one)){
//            新增就行了。
            Account build = Account.builder()
                    .uid(user.getUid())
                    .cardno("123456789")
                    .remaining(Double.valueOf(money))
                    .build();
            one = build;
        }else{
            one.setRemaining(one.getRemaining() + Double.valueOf(money));
        }
//        做更新。
        this.accountService.saveOrUpdate(one);
    }

    /**
     * 转账
     * @param money
     */
    @DeleteMapping("trans")
    public void transMoney(@RequestParam("money") double money){
        LambdaQueryWrapper<Account> wrapper = Wrappers.<Account>lambdaQuery()
                .eq(Account::getUid, user.getUid());
        Account one = this.accountService.getOne(wrapper);
        double v = money*0.0005;
        double pay = 0;
        if(ObjectUtils.isEmpty(one)){
            return;
        }
        if(one.getRemaining()<money-(money*0.0005)){
            return;
        }
        if(v <2){
            pay = 2;
        }else if(v >20){
            pay = 20;
        }else{
            pay = v;
        }
        one.setRemaining(one.getRemaining() -(money-v));
        this.accountService.updateById(one);
    }

    /**
     * 取钱。
     * @param money
     */
    @PostMapping("fetch")
    public void fetchMoney(@RequestParam("money") double money){
        LambdaQueryWrapper<Account> wrapper = Wrappers.<Account>lambdaQuery()
                .eq(Account::getUid, user.getUid());
        Account one = this.accountService.getOne(wrapper);
        if(ObjectUtils.isEmpty(one)){
            return;
        }
        if(one.getRemaining()<money){
            return;
        }
        one.setRemaining(one.getRemaining() - money);
        this.accountService.updateById(one);
    }

}
